#!/usr/bin/env python3
"""
测试运行脚本
"""
import subprocess
import sys
import os
from pathlib import Path

def run_tests(test_type="all"):
    """运行测试"""
    project_root = Path(__file__).parent
    os.chdir(project_root)
    
    # 激活虚拟环境并运行测试
    venv_python = project_root / ".venv" / "Scripts" / "python.exe"
    
    if not venv_python.exists():
        print("错误: 虚拟环境不存在，请先创建虚拟环境")
        return False
    
    # 构建测试命令
    cmd = [str(venv_python), "-m", "pytest"]
    
    if test_type == "unit":
        cmd.extend(["-m", "unit"])
    elif test_type == "integration":
        cmd.extend(["-m", "integration"])
    elif test_type == "fast":
        cmd.extend(["-m", "not slow"])
    
    # 添加覆盖率报告
    cmd.extend(["--cov=.", "--cov-report=term-missing", "--cov-report=html"])
    
    print(f"运行命令: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, check=True)
        print("测试运行成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"测试运行失败，返回码: {e.returncode}")
        return False
    except Exception as e:
        print(f"运行测试时发生错误: {e}")
        return False

def main():
    """主函数"""
    if len(sys.argv) > 1:
        test_type = sys.argv[1]
    else:
        test_type = "all"
    
    print(f"开始运行{test_type}测试...")
    
    success = run_tests(test_type)
    
    if success:
        print("测试完成！")
        if Path("htmlcov").exists():
            print("覆盖率报告已生成到 htmlcov/index.html")
    else:
        print("测试失败！")
        sys.exit(1)

if __name__ == "__main__":
    main()